#!/usr/bin/env bash
set -o errexit
set -o pipefail

if [ -z "$SAUCE_TUNNEL_NAME" ]; then
  echo "SAUCE_TUNNEL_NAME must be set" 1>&2
  exit 1
fi

outfile=`mktemp`
echo "Starting Sauce Connect"
sc legacy --proxy-localhost --tunnel-domains localhost --region us-west \
  -u "$SAUCE_USERNAME" -k "$SAUCE_ACCESS_KEY" \
  -X 4445 -i "$SAUCE_TUNNEL_NAME" 2>&1 | tee "$outfile" &

while ! fgrep "Sauce Connect is up, you may start your tests" "$outfile" > /dev/null; do
    sleep 1
done

if ! nc -z localhost 4445; then
    echo "Can't connect to Sauce tunnel"
    killall sc
    exit 1
fi
